package com.rtsapp.server.utils;

import com.rtsapp.server.logger.Logger;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AESUtils {

    private static final Logger logger =com.rtsapp.server.logger.LoggerFactory.getLogger(AESUtils.class);

    private static SecretKeySpec getKey(String password)
            throws NoSuchAlgorithmException {
        byte[] pwd = password.getBytes();
        byte[] key = new byte[16];
        for (int i = 0; i < key.length; i++) {
            if (i < pwd.length) {
                key[i] = pwd[i];
            } else {
                key[i] = 0xF;
            }
        }
        return new SecretKeySpec(key, "AES");
    }

    public static String encrypt(String content, String password) {
        try {

            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = NumberUtils.parseHexStr2Byte(content);
            cipher.init(Cipher.ENCRYPT_MODE, getKey(password));// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return NumberUtils.parseByte2HexStr(result); // 加密
        } catch (NoSuchAlgorithmException e) {
            logger.error("NoSuchAlgorithmException", e);
        } catch (NoSuchPaddingException e) {
            logger.error("NoSuchPaddingException", e);
        } catch (InvalidKeyException e) {
            logger.error("InvalidKeyException", e);
        } catch (IllegalBlockSizeException e) {
            logger.error("IllegalBlockSizeException", e);
        } catch (BadPaddingException e) {
            logger.warn("BadPaddingException", e);
        }
        return null;
    }

    public static String decrypt(String content, String password) {
        try {
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, getKey(password));// 初始化
            byte[] result = cipher.doFinal(NumberUtils
                    .parseHexStr2Byte(content));
            return NumberUtils.parseByte2HexStr(result); // 加密
        } catch (NoSuchAlgorithmException e) {
            logger.error("NoSuchAlgorithmException", e);
        } catch (NoSuchPaddingException e) {
            logger.error("NoSuchPaddingException",e);
        } catch (InvalidKeyException e) {
            logger.error("InvalidKeyException",e);
        } catch (IllegalBlockSizeException e) {
            logger.error("IllegalBlockSizeException", e);
        } catch (BadPaddingException e) {
            logger.warn("BadPaddingException",e);
        }
        return null;
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
